﻿using NExt.Handler.Base.Common.Cache;
using NExt.Handler.Base.Default;
using System.IO;
using NExt.Handler.Component.Common;
using NExt.Handler.Base.Common.Manager;
using System.Web;
using NExt.Serialization;

namespace NExt.Handler.Component.Default.RemoteInstance
{
    public class ResultContentBuilder : ConcurrentCache<ResultContentBuilder, string, string>, IContentBuilder
    {
        public string Build(HttpContext context)
        {
            string fileName = Path.GetFileNameWithoutExtension(context.Request.Path);
            string typeName = context.Request.Headers[HeaderKey.CLASS_TYPE];
            string key = string.Format("{0}.{1}", typeName, fileName);
            string content = GetOrAdd(key, () => BuildContent(typeName, fileName));
            return content;
        }

        private string BuildContent(string typeName, string fileName)
        {
            object instance = InstanceManager.GetInstance(fileName, typeName);
            string content = JsonSerializer.Serialize(instance);
            return content;
        }
    }
}
